package com.hck.taozi_help.module.yuyin;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.hck.taozi_help.R;
import com.hck.taozi_help.utils.LogUtil;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechEvent;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.VoiceWakeuper;
import com.iflytek.cloud.WakeuperListener;
import com.iflytek.cloud.WakeuperResult;
import com.iflytek.cloud.util.ResourceUtil;

import org.json.JSONException;
import org.json.JSONObject;

public class KeDaYuYingManger {
    private int curThresh = 1450;
    private String keep_alive = "1";
    private String ivwNetMode = "0";
    private VoiceWakeuper mIvw;
     private OnCallBackListener listener;
    public interface OnCallBackListener{
        void wakeApp();
    }

    WakeuperListener mWakeuperListener = new WakeuperListener() {

        @Override
        public void onResult(WakeuperResult result) {
            listener.wakeApp();
            try {
                String text = result.getResultString();
                JSONObject object;
                object = new JSONObject(text);
                StringBuffer buffer = new StringBuffer();
                buffer.append("【RAW】 " + text);
                buffer.append("\n");
                buffer.append("【操作类型】" + object.optString("sst"));
                buffer.append("\n");
                buffer.append("【唤醒词id】" + object.optString("id"));
                buffer.append("\n");
                buffer.append("【得分】" + object.optString("score"));
                buffer.append("\n");
                buffer.append("【前端点】" + object.optString("bos"));
                buffer.append("\n");
                buffer.append("【尾端点】" + object.optString("eos"));
                LogUtil.log("onResult: "+buffer.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(SpeechError error) {
            LogUtil.log("onError: "+error.toString());
        }

        @Override
        public void onBeginOfSpeech() {
            LogUtil.log("onBeginOfSpeech: ");
        }

        @Override
        public void onEvent(int eventType, int isLast, int arg2, Bundle obj) {
            LogUtil.log("onEventonEvent: ");
            switch (eventType) {
                // EVENT_RECORD_DATA 事件仅在 NOTIFY_RECORD_DATA 参数值为 真 时返回
                case SpeechEvent.EVENT_RECORD_DATA:
                    final byte[] audio = obj.getByteArray(SpeechEvent.KEY_EVENT_RECORD_DATA);
                    break;
            }
        }

        @Override
        public void onVolumeChanged(int volume) {

        }
    };

    public static void initializeMsc(Context context){

        // 应用程序入口处调用,避免手机内存过小,杀死后台进程后通过历史intent进入Activity造成SpeechUtility对象为null
        // 注意：此接口在非主进程调用会返回null对象，如需在非主进程使用语音功能，请增加参数：SpeechConstant.FORCE_LOGIN+"=true"
        // 参数间使用“,”分隔。
        // 设置你申请的应用appid
        // 注意： appid 必须和下载的SDK保持一致，否则会出现10407错误
        StringBuffer param = new StringBuffer();
        param.append("appid=" + context.getString(R.string.app_yuying_id));
        param.append(",");
        // 设置使用v5+
        param.append(SpeechConstant.ENGINE_MODE + "=" + SpeechConstant.MODE_MSC);
        SpeechUtility.createUtility(context, param.toString());
    }

   public void stop(){
        if (mIvw!=null){
            mIvw.stopListening();
        }
   }

   public void start(){
        if (mIvw!=null){
            mIvw.startListening(mWakeuperListener);
        }

   }
    public void start(Context context,OnCallBackListener listener) {
        LogUtil.log("start startstartstart");
        if (null == VoiceWakeuper.createWakeuper(context, null)) {
           LogUtil.log("start errorr");
            return;
        }

        this.listener=listener;
        // 初始化唤醒对象
        mIvw = VoiceWakeuper.createWakeuper(context, null);
        if (mIvw != null) {
            // 清空参数
            mIvw.setParameter(SpeechConstant.PARAMS, null);
            // 唤醒门限值，根据资源携带的唤醒词个数按照“id:门限;id:门限”的格式传入
            mIvw.setParameter(SpeechConstant.IVW_THRESHOLD, "0:" + curThresh);
            // 设置唤醒模式
            mIvw.setParameter(SpeechConstant.IVW_SST, "wakeup");
            // 设置持续进行唤醒
            mIvw.setParameter(SpeechConstant.KEEP_ALIVE, keep_alive);
            // 设置闭环优化网络模式
            mIvw.setParameter(SpeechConstant.IVW_NET_MODE, ivwNetMode);
            // 设置唤醒资源路径
            mIvw.setParameter(SpeechConstant.IVW_RES_PATH, getResource(context));
            // 设置唤醒录音保存路径，保存最近一分钟的音频
            // mIvw.setParameter(SpeechConstant.IVW_AUDIO_PATH,
            //        getExternalFilesDir("msc").getAbsolutePath() + "/ivw.wav");
            mIvw.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
            // 如有需要，设置 NOTIFY_RECORD_DATA 以实时通过 onEvent 返回录音音频流字节
            //mIvw.setParameter( SpeechConstant.NOTIFY_RECORD_DATA, "1" );
            // 启动唤醒
            /*	mIvw.setParameter(SpeechConstant.AUDIO_SOURCE, "-1");*/
            mIvw.startListening(mWakeuperListener);
        }


    }
    private String getResource(Context context) {
        final String resPath = ResourceUtil.generateResourcePath(context, ResourceUtil.RESOURCE_TYPE.assets, "ivw/" + context.getResources().getString(R.string.app_yuying_id) + ".jet");
        return resPath;
    }
}
